<template>
  <div class="fulltable">
    <div class="full">
      <div class="add">  
        <button class="button" @click="showAddModal = true">➕新增</button>  
      </div>  

      <div class="search-box">  
        <el-select v-model="selectedType" placeholder="请选择类型" style="width: 200px; margin-right: 10px;" clearable>  
          <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>  
        </el-select>  
        
        <el-select v-model="selectedState" placeholder="请选择状态" style="width: 200px; margin-right: 10px;" clearable>  
          <el-option v-for="item in selectstateOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>  
        </el-select>  

        <el-input v-model="searchTitle" placeholder="搜索标题" style="width: 200px; margin-right: 10px;" clearable></el-input>  
        <el-input v-model="searchPromoter" placeholder="搜索发起人" style="width: 200px; margin-right: 10px;" clearable></el-input>  
      </div>
    <el-table
     :data="filteredData.slice((currentPage - 1) * pageSize, currentPage * pageSize)"
    :height="tableHeight"
    border
    style="width: 100%">
    <el-table-column
      prop="type"
      label="类型"
      width="100">
    </el-table-column>
    <el-table-column
      prop="state"
      label="状态"
      width="100"
      >
    </el-table-column>
    <el-table-column
      prop="title"
      label="标题"
      width="150">
    </el-table-column>
     <el-table-column
      prop="starttime"
      label="开始时间"
      width="180">
    </el-table-column>
        <el-table-column
      prop="deadline"
      label="结束时间"
      width="180">
    </el-table-column>
    <el-table-column
      prop="promoter"
      label="发起人"
      width="120">
    </el-table-column>
    <el-table-column
      prop="deptname"
      label="部门"
      width="120">
    </el-table-column>
        <el-table-column label="操作">  
          <template slot-scope="scope">  
            <el-button type="primary" size="small" @click="viewItem(scope.row)">详情</el-button>  
            <el-button 
              type="warning" 
              size="small" 
              @click="handleEdit(scope.row)"
              v-if="canDelete(scope.row)">编辑</el-button>
              <el-button 
              type="primary" 
              size="small" 
              @click="handleReminder(scope.row)"
              v-if="canDelete(scope.row)">提醒</el-button>
            <el-button 
              v-if="canDelete(scope.row)"
              type="danger" 
              size="small" 
              @click="deleteItem(scope.row)"
            >删除</el-button>  
          </template>  
        </el-table-column>  
  </el-table>
      <div class="paging">
      <el-pagination  
        @size-change="handleSizeChange"  
        @current-change="handleCurrentChange"  
        :current-page="currentPage"  
        :page-sizes="[5,10, 20, 40, 60]"  
        :page-size="pageSize"  
        :pager-count="4"
        layout="total, sizes, prev, pager, next, jumper"  
        :total="scheduleData.length">  
      </el-pagination> 
      </div>
  </div>
<!-- 新增弹窗 -->  
<el-dialog title="新增日程" :visible.sync="showAddModal" width="30%">  
  <el-form :model="newItem" label-width="80px" ref="newItemForm">  
    <el-form-item label="类型" prop="type" :rules="[{ required: true, message: '类型不能为空' }]">  
      <el-select v-model="newItem.type" placeholder="请选择类型">  
        <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value">  
        </el-option>  
      </el-select>  
    </el-form-item>
    <el-form-item label="状态" prop="state" :rules="[{ required: true, message: '状态不能为空' }]">  
      <el-select v-model="newItem.state" placeholder="请选择状态">  
        <el-option v-for="item in stateOptions" :key="item.value" :label="item.label" :value="item.value">  
        </el-option>  
      </el-select>  
    </el-form-item>
    <el-form-item label="标题" prop="title" :rules="[{ required: true, message: '标题不能为空' }]">  
      <el-input v-model="newItem.title"></el-input>  
    </el-form-item>  
        <el-form-item label="描述" prop="desc" :rules="[{ required: true, message: '详细描述不能为空' }]">  
          <el-input v-model="newItem.desc"></el-input>  
        </el-form-item>  
        <el-form-item label="开始时间" prop="starttime" :rules="[{ required: true, message: '开始时间不能为空' }]">  
          <el-date-picker 
            v-model="newItem.starttime" 
            type="datetime" 
            placeholder="选择开始时间">
          </el-date-picker>  
        </el-form-item>  
        <el-form-item label="结束时间" prop="deadline" :rules="[{ required: true, message: '结束时间不能为空' }]">  
          <el-date-picker 
            v-model="newItem.deadline" 
            type="datetime" 
            placeholder="选择结束时间">
          </el-date-picker>  
        </el-form-item>
      <el-form-item label="部门" prop="deptname" >  
        <el-select v-model="newItem.deptname" filterable placeholder="请选择部门,不选则默认发所有人" style="width:400px">  
          <el-option v-for="item in deptList" :key="item.id" :label="item.deptname" :value="item.id"></el-option>  
        </el-select>  
      </el-form-item> 
      <el-form-item label="接收人" prop="receiverList">  
        <el-row>
          <el-col :span="20">
            <el-select 
              v-model="receiverList" 
              multiple 
              placeholder="请选择接收人，不填则视为发部门下所有人" 
              style="width:100%">  
              <el-option 
                v-for="item in userByDept" 
                :key="item.id" 
                :label="item.realname" 
                :value="item.id">
              </el-option>  
            </el-select>  
          </el-col>
          <el-col :span="4" style="padding-left: 10px; line-height: 40px;">
            <span style="color: #409EFF;">已选：{{ receiverList.length }}人</span>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="会议室" prop="boardroomId" v-if="newItem.type === '会议'">
        <el-row>
          <el-col :span="18">
            <el-select 
              v-model="newItem.boardroomId" 
              placeholder="请选择会议室">
              <el-option 
                v-for="room in boardroomList" 
                :key="room.id" 
                :label="'房间号: ' + room.cno + ' (容纳: ' + room.number + '人)'" 
                :value="room.id">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="showBoardroomSchedule">查看预约情况</el-button>
          </el-col>
        </el-row>
      </el-form-item>
  </el-form>  
  <span slot="footer" class="dialog-footer">  
    <el-button @click="handleCancelAdd">取 消</el-button>  
    <el-button type="warning" @click="resetForm">重 置</el-button>  
    <el-button type="primary" @click="saveNewItem">确 定</el-button>  
  </span>  
</el-dialog>
<!-- 查看详情弹窗 -->  
<!-- 查看详情弹窗 -->  
<el-dialog title="日程详情" :visible.sync="showDetailModal" width="60%">  
  <el-form :model="detailItem" label-width="80px">  
    <el-row>  
      <el-col :span="12">  
        <el-form-item label="类型">  
          <el-input v-model="detailItem.type" disabled></el-input>  
        </el-form-item>  
      </el-col>  
      <el-col :span="12">  
        <el-form-item label="状态">  
          <el-input v-model="detailItem.state" disabled></el-input>  
        </el-form-item>  
      </el-col>  
    </el-row>  
    <el-row>  
      <el-col :span="12">  
        <el-form-item label="标题">  
          <el-input v-model="detailItem.title" disabled></el-input>  
        </el-form-item>  
      </el-col>  
      <el-col :span="12">  
        <el-form-item label="描述">  
          <el-input v-model="detailItem.desc" disabled></el-input>  
        </el-form-item>  
      </el-col>  
    </el-row>  
    <el-row>  
      <el-col :span="12">  
        <el-form-item label="开始时间">  
          <el-input v-model="detailItem.starttime" disabled></el-input>  
        </el-form-item>  
      </el-col>  
      <el-col :span="12">  
        <el-form-item label="结束时间">  
          <el-input v-model="detailItem.deadline" disabled></el-input>  
        </el-form-item>  
      </el-col>  
    </el-row>  
    <el-row>  
      <el-col :span="12">  
        <el-form-item label="发起人">  
          <el-input v-model="detailItem.promoter" disabled></el-input>  
        </el-form-item>  
      </el-col>  
      <el-col :span="12">  
        <el-form-item label="部门">  
          <el-input v-model="detailItem.deptname" disabled></el-input>  
        </el-form-item>  
      </el-col>  
    </el-row>  
    <el-row>  
      <el-col :span="12">  
        <el-form-item label="会议室">  
          <el-input v-model="detailItem.boardroom" disabled></el-input>  
        </el-form-item>  
      </el-col> 
      <el-col :span="12">  
        <el-form-item label="接收人">  
          <el-input type="textarea" v-model="detailItem.recipient" disabled></el-input>  
        </el-form-item>  
      </el-col>  
    </el-row>  
  </el-form>  
  <span slot="footer" class="dialog-footer">  
    <el-button @click="showDetailModal = false">取 消</el-button>  
  </span>  
</el-dialog>

<!-- 修改会议室预约情况弹窗 -->
<el-dialog 
  title="会议室预约情况" 
  :visible.sync="showScheduleModal" 
  :close-on-click-modal="false"
  width="70%">
  <!-- 添加搜索条件 -->
  <div class="search-box" style="margin-bottom: 20px;">
    <el-select
      v-model="boardroomSearch.cno"
      placeholder="选择会议室"
      style="width: 200px; margin-right: 10px;"
      clearable
        filterable>
      <el-option
        v-for="room in boardroomList"
        :key="room.cno"
        :label="room.cno"
        :value="room.cno">
      </el-option>
    </el-select>
    <el-date-picker
      v-model="boardroomSearch.starttime"
      type="datetime"
      placeholder="开始时间"
      style="width: 220px; margin-right: 10px;"
      clearable>
    </el-date-picker>
    <el-date-picker
      v-model="boardroomSearch.deadline"
      type="datetime"
      placeholder="结束时间"
      style="width: 220px; margin-right: 10px;"
      clearable>
    </el-date-picker>
    <el-button type="primary" @click="searchBoardroomSchedules">搜索</el-button>
    <el-button @click="resetBoardroomSearch">重置</el-button>
  </div>

  <el-table 
    :data="paginatedBoardroomSchedules" 
    border
    v-loading="loading"
    style="text-align: center;">
    <el-table-column prop="cno" label="会议室号" width="120"></el-table-column>
    <el-table-column prop="starttime" label="开始时间" width="180"></el-table-column>
    <el-table-column prop="deadline" label="结束时间" width="180"></el-table-column>
  </el-table>

  <el-pagination
    @current-change="handlePageChange"
    :current-page="currentBoardroomPage"
    :page-size="10"
    :total="filteredBoardroomSchedules.length"
    layout="total, prev, pager, next">
  </el-pagination>

  <span slot="footer" class="dialog-footer">
    <el-button @click="showScheduleModal = false">关闭</el-button>
  </span>
</el-dialog>

<!-- 添加编辑弹窗 -->
<el-dialog title="编辑日程" :visible.sync="showEditModal" width="30%">  
  <el-form :model="editItem" label-width="80px" ref="editItemForm">  
    <el-form-item label="类型" prop="type" >  
      <div style="display: flex; align-items: center;">
        <el-select v-model="editItem.type" placeholder="请选择类型" style="width: 200px;">  
          <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>  
        </el-select>
        <span style="margin-left: 10px; color: #409EFF;">当前: {{ currentItem.type }}</span>
      </div>  
    </el-form-item>
    <el-form-item label="状态" prop="state" >  
      <div style="display: flex; align-items: center;">
        <el-select v-model="editItem.state" placeholder="请选择状态" style="width: 200px;">  
          <el-option v-for="item in stateOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>  
        </el-select>
        <span style="margin-left: 10px; color: #409EFF;">当前: {{ currentItem.state }}</span>
      </div>  
    </el-form-item>
    <el-form-item label="标题" prop="title" >  
      <el-input v-model="editItem.title"></el-input>  
    </el-form-item>  
    <el-form-item label="描述" prop="desc" >  
      <el-input v-model="editItem.desc"></el-input>  
    </el-form-item>  
    <el-form-item label="开始时间" prop="starttime" >  
      <el-date-picker 
        v-model="editItem.starttime" 
        type="datetime" 
        placeholder="选择开始时间">
      </el-date-picker>  
    </el-form-item>  
    <el-form-item label="结束时间" prop="deadline" >  
      <el-date-picker 
        v-model="editItem.deadline" 
        type="datetime" 
        placeholder="选择结束时间">
      </el-date-picker>  
    </el-form-item>
    <el-form-item label="部门" prop="deptname">  
      <div style="display: flex; align-items: center;">
        <el-select v-model="editItem.deptname" filterable placeholder="请选择部门" style="width: 200px;">  
          <el-option v-for="item in deptList" :key="item.id" :label="item.deptname" :value="item.id"></el-option>  
        </el-select>
        <span style="margin-left: 10px; color: #409EFF;">当前: {{ currentItem.deptname }}</span>
      </div>  
    </el-form-item> 
    <el-form-item label="接收人" prop="receiverList">  
      <div style="display: flex; align-items: flex-start;">
        <el-select 
          v-model="editReceiverList" 
          multiple 
          placeholder="请选择接收人" 
          style="width: 200px;">  
          <el-option 
            v-for="item in userByDept" 
            :key="item.id" 
            :label="item.realname" 
            :value="item.id">
          </el-option>  
        </el-select>
        <div style="margin-left: 10px;">
          <span style="color: #409EFF; display: block; margin-bottom: 5px;">当前接收人:</span>
          <el-input
            type="textarea"
            v-model="currentItem.recipient"
            :rows="3"
            readonly
            style="width: 200px;"
          ></el-input>
        </div>
      </div>  
    </el-form-item>
    <el-form-item label="会议室" prop="boardroomId" v-if="editItem.type === '会议'">
      <div style="display: flex; align-items: center;">
        <el-select 
          v-model="editItem.boardroomId" 
          placeholder="请选择会议室"
          style="width: 200px;">
          <el-option 
            v-for="room in boardroomList" 
            :key="room.id" 
            :label="'房间号: ' + room.cno + ' (容纳: ' + room.number + '人)'" 
            :value="room.id">
          </el-option>
        </el-select>
        <span style="margin-left: 10px; color: #409EFF;">当前: {{ currentItem.boardroom }}</span>
      </div>
    </el-form-item>
  </el-form>  
  <span slot="footer" class="dialog-footer">  
    <el-button @click="showEditModal = false">取 消</el-button>  
    <el-button type="primary" @click="saveEditItem">确 定</el-button>  
  </span>  
</el-dialog>
  </div>
</template>

<script>
import {reminder,getScheduleList,addSchedule,getBoardroomSchedules,deleteScheduleById,getScheduleDetailById,checkBoardroomSchedule,updateSchedule} from '@/api/schedule';
import {getUserList,getUserByDeptId} from '@/api/user';
import {getDeptList} from '@/api/dept';
import {getBoardroomList,getICanUseBoardroomList} from '@/api/boardroom';
import { jwtDecode } from 'jwt-decode';
import {addLog} from '@/api/log';
export default {
  data(){
    return {
      scheduleData:[],
        currentPage: 1,  
        pageSize: 5  ,
        tableHeight: 300,  
        maxTableHeight: 700, // 最大高度 600px  
        minTableHeight: 300,
        showAddModal: false, 
        showDetailModal: false,  
        selectedType: null, // 任务类型选择  
        selectedState: null, // 任务状态选择  
        searchTitle: '', // 标题搜索  
        searchPromoter: '', // 发起人搜索  
        detailItem: {},   
        newItem: {  
          type: '',  
          state: '',  
          title: '',  
          desc:'',
          starttime: '',  
          deadline: '',  
          promoter: '',  
          deptname: '',
          receiverList:[],
          boardroomId: null,    
        },
        typeOptions: [  
          {label:'会议',value:'会议'},
          { label: '假期安排', value: '假期安排' }
        ],
        stateOptions: [  
          { label: '一般', value: 3 },  
          { label: '重要', value: 2 },  
          { label: '紧急', value: 1 }  
        ],
        selectstateOptions: [  
          { label: '一般', value: '一般' },  
          { label: '重要', value: '重要' },  
          { label: '紧急', value: '紧急' },
        ],
        userList:[],
        deptList:[],
        userByDept:[],
        receiverList: [],
        boardroomList: [], // 新增会议室列表
        showScheduleModal: false,
        boardroomSchedules: [],
        boardroomSearch: {
          cno: '',
          starttime: '',
          deadline: ''
        },
        loading: false,
        currentUserRole: this.getUserRole(),
        currentUserId: this.getUserId(),
        currentUserDeptId: this.getUserDeptId(),
        showEditModal: false,
        editItem: {
          id: '',
          type: '',
          state: '',
          title: '',
          desc: '',
          starttime: '',
          deadline: '',
          deptname: '',
          receiverList: [],
          boardroomId: null
        },
        editReceiverList: [],
        currentItem: {},
        currentBoardroomPage: 1,
        logItem:{
              mn:'',
              opn:'',
              res:''
      },
      baseType:'',
    }
  },
  computed: {  
  filteredData() {  
    return this.scheduleData.filter(item => {  
      const matchesType = this.selectedType ? item.type === this.selectedType : true;  
      const matchesState = this.selectedState ? item.state === this.selectedState : true;  
      const matchesTitle = item.title.includes(this.searchTitle);  
      const matchesPromoter = item.promoter.includes(this.searchPromoter);  

      return matchesType && matchesState && matchesTitle && matchesPromoter;  
    });  
  },
  filteredBoardroomSchedules() {
    if (!this.boardroomSchedules) {
      return [];
    }

    // 如果所有搜索条件都为空，返回全部数据
    if (!this.boardroomSearch.cno && !this.boardroomSearch.starttime && !this.boardroomSearch.deadline) {
      return this.boardroomSchedules;
    }

    // 否则进行条件过滤
    return this.boardroomSchedules.filter(item => {
      // 会议室号匹配
      const matchCno = !this.boardroomSearch.cno || (item.cno && item.cno.toString().includes(this.boardroomSearch.cno));
      
      // 时间匹配
      let matchTime = true;
      if (this.boardroomSearch.starttime && this.boardroomSearch.deadline) {
        // 有开始和结束时间时，查找重叠的预约
        const searchStart = new Date(this.boardroomSearch.starttime).getTime();
        const searchEnd = new Date(this.boardroomSearch.deadline).getTime();
        const itemStart = new Date(item.starttime).getTime();
        const itemEnd = new Date(item.deadline).getTime();

        matchTime = (
          (searchStart >= itemStart && searchStart <= itemEnd) || // 开始时间在范围内
          (searchEnd >= itemStart && searchEnd <= itemEnd) || // 结束时间在范围内
          (searchStart <= itemStart && searchEnd >= itemEnd) // 完全包含
        );
      } else if (this.boardroomSearch.starttime) {
        // 只有开始时间时，查找使用时间在开始时间之后的预约
        const searchStart = new Date(this.boardroomSearch.starttime).getTime();
        const itemStart = new Date(item.starttime).getTime();
        const itemEnd = new Date(item.deadline).getTime();
        matchTime = searchStart >= itemStart && searchStart <= itemEnd;
      } else if (this.boardroomSearch.deadline) {
        // 只有结束时间时，查找结束时间在使用时间范围内的预约
        const searchEnd = new Date(this.boardroomSearch.deadline).getTime();
        const itemStart = new Date(item.starttime).getTime();
        const itemEnd = new Date(item.deadline).getTime();
        matchTime = searchEnd >= itemStart && searchEnd <= itemEnd;
      }

      return matchCno && matchTime;
    });
  },
  paginatedBoardroomSchedules() {
    const start = (this.currentBoardroomPage - 1) * 10;
    return this.filteredBoardroomSchedules.slice(start, start + 10);
  }
},
  created(){
    getScheduleList().then(response=>{
      this.scheduleData = response.data
      this.calculateTableHeight() 
      console.log(response.data)
    }).catch(error =>{
      console.log(error)
      this.tableHeight = this.minTableHeight  
    })

    this.getUsers();
    this.getDepts();
    
  },
  watch:{
  currentPage() {  
    this.calculateTableHeight()  
  },  
  pageSize() {  
    this.calculateTableHeight()  
  },
  'newItem.deptname'(newVal) { 
    if(newVal){ 
    this.getUserByDept(newVal);  
    }
  },
  'newItem.boardroomId': {
      handler: 'checkBoardroomAvailability'
    },
    'newItem.starttime': {
      handler(newVal) {
        if (newVal && this.newItem.deadline) {
          this.getBoardrooms(); // 只有在开始时间和结束时间都存在时才调用
        }
      }
    },
    'newItem.deadline': {
      handler(newVal) {
        if (newVal && this.newItem.starttime) {
          this.getBoardrooms(); // 只有在开始时间和结束时间都存在时才调用
        }
      }
    },
    'receiverList': {
      handler: 'checkBoardroomAvailability'
    },
    boardroomSchedules: {
      handler(newVal) {
        console.log('boardroomSchedules changed:', newVal);
      },
      deep: true
    },
    boardroomSearch: {
      handler(newVal) {
        console.log('boardroomSearch changed:', newVal);
      },
      deep: true
    },
    'editItem.deptname'(newVal) {
      if (newVal) {
        this.getUserByDept(newVal);
      }
    },
    'editItem.boardroomId': {
      handler: 'checkBoardroomAvailability'
    },
    'editItem.starttime': {
      handler: 'checkBoardroomAvailability'
    },
    'editItem.deadline': {
      handler: 'checkBoardroomAvailability'
    },
    'editReceiverList': {
      handler: 'checkBoardroomAvailability'
    }
  },
  methods:{
    getBoardrooms() {
      const data = {
        boardroomId:0,
        starttime: this.formatDateTime(this.newItem.starttime),
        deadline: this.formatDateTime(this.newItem.deadline)
      };
      console.log("data",data)
      getICanUseBoardroomList(data).then(response => {
        this.boardroomList = response.data;
      }).catch(error => {
        console.error('获取会议室列表失败:', error);
        this.$message.error('获取会议室列表失败');
      });
    },
    checkBoardroomAvailability() {
      if (!this.newItem.boardroomId || !this.newItem.starttime || !this.newItem.deadline) {
        return;
      }

      // 获取选中的会议室信息
      const selectedRoom = this.boardroomList.find(room => room.id === this.newItem.boardroomId);
      
      // 计算参会人数（接收人列表 + 发起人）
      const attendeesCount = (this.receiverList ? this.receiverList.length : 0) ;
      
      // 检查人数是否超出会议室容量
      if (attendeesCount > selectedRoom.number) {
        this.$message.warning(`当前参会人数(${attendeesCount}人)超出会议室容量(${selectedRoom.number}人)`);
        this.newItem.boardroomId = null;
        return;
      }

      const data = {
        boardroomId: this.newItem.boardroomId,
        starttime: this.formatDateTime(this.newItem.starttime),
        deadline: this.formatDateTime(this.newItem.deadline)
      };

      checkBoardroomSchedule(data).then(response => {
        if (response.data.isOccupied) {
          this.$message.warning('该时段会议室已被占用，请选择其他时间或会议室');
          this.newItem.boardroomId = null;
        } else {
          this.$message.success('该时段会议室可用');
        }
      }).catch(error => {
        console.error('检查会议室可用性失败:', error);
        this.$message.error('检查会议室可用性失败');
      });
    },
    formatDateTime(date) {
      if (!date) return '';
      return new Date(date).toISOString().slice(0, 19).replace('T', ' ');
    },

    handleSizeChange(val) {  
      this.pageSize = val;  
      this.currentPage = 1;  
      this.logItem.mn = "handleSizeChange";
      this.logItem.opn = "改变每页显示的日程数量-日程管理";
      this.logItem.res = "true";
      addLog(this.logItem);
    },  
    handleCurrentChange(val) {  
      this.currentPage = val;  
      this.logItem.mn = "handleCurrentChange";
      this.logItem.opn = "改变页码-日程管理";
      this.logItem.res = "true";
      addLog(this.logItem);
    },  
  calculateTableHeight() {  
    // 获取当前页展示的数据量  
    const currentPageData = this.scheduleData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);  
    
    // 每行高度为 50px，再加上表头高度 50px，得到总高度  
    let height = (currentPageData.length + 1) * 60 
    // 限制高度在 minTableHeight 和 maxTableHeight 之间  
    this.tableHeight = Math.max(this.minTableHeight, Math.min(height, this.maxTableHeight))  
  },
    saveNewItem() {
      this.$refs.newItemForm.validate((valid) => {
        if (valid) {
          // 如果是日程提醒类型,需要验证是否选择了会议室
          if (this.newItem.type === '日程提醒' && !this.newItem.boardroomId) {
            this.$message.warning('请选择会议室');
            return;
          }

          this.newItem.receiverList = this.receiverList;
          addSchedule(this.newItem)
            .then(response => {
              this.$message.success('新日程添加成功');
              this.logItem.mn = "saveNewItem";
              this.logItem.opn = "新增日程";
              this.logItem.res = "true";
              addLog(this.logItem);
              window.location.reload();
              this.showAddModal = false;
              getScheduleList();
            })
            .catch(error => {
              this.logItem.mn = "saveNewItem";
              this.logItem.opn = "新增日程";
              this.logItem.res = "false";
              addLog(this.logItem);
              this.$message.error('新日程添加失败');
              console.error(error);
            });
        } else {
          return false;
        }
      });
    },
  getUsers(){
      getUserList().then((response) => {  
        console.log(response.data)
        this.userList = response.data;  
      });  
    },
  getDepts(){
    getDeptList().then((response) => {  
      console.log(response.data)
      this.deptList = response.data;  
    });  
    },
  handleDeptChange(deptId) {  
    this.getUserByDept(deptId);  
  },
  getUserByDept(deptId) {  
    getUserByDeptId(deptId).then((response) => {  
      this.userByDept = response.data;  
      console.log("部门成员：",this.userByDept)
    });  
  },
  handleCancelAdd() {
      this.showAddModal = false;
      this.newItem = {
        type: '',
        state: '',
        title: '',
        desc: '',
        starttime: '',
        deadline: '',
        promoter: '',
        deptname: '',
        receiverList: [],
        boardroomId: null // 新增会议室ID重置
      };
    },
  deleteItem(row) {  
  this.$confirm('确定要删除此日程吗?', '警告', {  
    confirmButtonText: '确定',  
    cancelButtonText: '取消',  
    type: 'warning'  
  }).then(() => {  
    // 调用删除 API  
    deleteScheduleById(row.id).then(response => {  
      // 从 scheduleData 中移除已删除的项  
      this.scheduleData = this.scheduleData.filter(item => item.id !== row.id);  
      this.logItem.mn = "deleteItem";
      this.logItem.opn = "删除日程";
      this.logItem.res = "true";
      addLog(this.logItem);
      this.$message.success('日程删除成功');  
      window.location.reload()  
    }).catch(error => {  
      console.error(error);  
      this.logItem.mn = "deleteItem";
      this.logItem.opn = "删除日程";
      this.logItem.res = "false";
      addLog(this.logItem);
      this.$message.error('日程删除失败');  
    });  
  }).catch(() => {  
    this.$message.info('已取消删除');  
  });  
},
  viewItem(row) {  
    getScheduleDetailById(row.id).then((response)=>{
        this.showDetailModal = true; // 显示详情弹窗  
        console.log(response.data);
        this.detailItem = response.data;
        if (this.detailItem.starttime) {  
            this.detailItem.starttime = this.detailItem.starttime.replace(/T/g, ' ');  
        }  
        if (this.detailItem.deadline) {  
            this.detailItem.deadline = this.detailItem.deadline.replace(/T/g, ' ');  
        }  
        this.logItem.mn = "viewItem";
        this.logItem.opn = "查看日程详情-日程管理";
        this.logItem.res = "true";
        addLog(this.logItem);
    }).catch(error =>{
      console.log(error);
      this.logItem.mn = "viewItem";
      this.logItem.opn = "查看日程详情-日程管理";
      this.logItem.res = "false";
      addLog(this.logItem);
      this.$message.error('查看日程失败');  
    })
  }, 
  showBoardroomSchedule() {
    getBoardroomSchedules().then(response => {
      this.boardroomSchedules = response.data.map(item => ({
        ...item,
        starttime: this.formatDateTime(item.starttime),
        deadline: this.formatDateTime(item.deadline)
      }));
      this.boardroomSearch.cno = '';
      this.boardroomSearch.starttime = '';
      this.boardroomSearch.deadline = '';
      this.currentBoardroomPage=1;
      this.showScheduleModal = true;
      this.logItem.mn = "showBoardroomSchedule";
      this.logItem.opn = "获取会议室预约情况-日程管理";
      this.logItem.res = "true";
      addLog(this.logItem);
    }).catch(error => {
      console.error('获取会议室预约情况失败:', error);
      this.logItem.mn = "showBoardroomSchedule";
      this.logItem.opn = "获取会议室预约情况-日程管理";
      this.logItem.res = "false";
      addLog(this.logItem);
      this.$message.error('获取会议室预约情况失败');
    });
  },
  searchBoardroomSchedules() {
    // 这里可以选择调用后端API进行搜索，或者使用前端过滤
    // 当前使用计算属性进行前端过滤
  },
  resetBoardroomSearch() {
    this.boardroomSearch = {
      cno: '',
      starttime: '',
      deadline: ''
    };
  },
  resetForm() {
    this.$refs.newItemForm.resetFields();
    this.newItem = {
      type: '',
      state: '',
      title: '',
      desc: '',
      starttime: '',
      deadline: '',
      promoter: '',
      deptname: '',
      receiverList: [],
      boardroomId: null
    };
    this.receiverList = [];
  },
  getUserRole() {
    const token = localStorage.getItem('token');
    if (token) {
      const decodedToken = jwtDecode(token);
      return decodedToken.role;
    }
    return null;
  },
  getUserId() {
    const token = localStorage.getItem('token');
    if (token) {
      const decodedToken = jwtDecode(token);
      return decodedToken.userId;
    }
    return null;
  },
  getUserDeptId() {
    const token = localStorage.getItem('token');
    if (token) {
      const decodedToken = jwtDecode(token);
      return decodedToken.deptId;
    }
    return null;
  },
  canDelete(row) {
    // SUPERMAN 可以删除所有
    if (this.currentUserRole === 'SUPERMAN') {
      return true;
    }
    
    // MANAGER 可以删除自己发布的或本部门的
    if (this.currentUserRole === 'MANAGER') {
      return row.promoterId === this.currentUserId || row.deptId === this.currentUserDeptId;
    }
    
    // NORMAL 只能删除自己发布的
    if (this.currentUserRole === 'NORMAL') {
      return row.promoterId === this.currentUserId;
    }
    
    return false;
  },
  handleReminder(row){
    console.log("提醒的数据",row)
    reminder(row.id).then((response)=>{
      console.log(response);
      this.$message.success("提醒成功")
      this.logItem.mn = "handleReminder";
      this.logItem.opn = "发布日程提醒";
      this.logItem.res = "true";
      addLog(this.logItem);
    }).catch(error=>{
      console.error(error);
      this.$message.error("提醒失败,十分钟内只能提醒一次");
      this.logItem.mn = "handleReminder";
      this.logItem.opn = "发布日程提醒";
      this.logItem.res = "false";
      addLog(this.logItem);
    })
  },
  handleEdit(row) {
    getScheduleDetailById(row.id).then((response) => {
      this.currentItem = response.data;
      // 初始化编辑表单
      this.editItem = {
        id: response.data.id,
        type: response.data.type,
        state: '',
        title: response.data.title,
        desc: response.data.desc,
        starttime: response.data.starttime,
        deadline: response.data.deadline,
        deptname: '',
        receiverList: [],
        boardroomId: null
      };
      this.baseType = response.data.type;
      if (response.data.deptid) {
        this.getUserByDept(response.data.deptid);
      }
      
      this.showEditModal = true;
    }).catch(error => {
      console.error('获取日程详情失败:', error);
      this.$message.error('获取日程详情失败');
    });
  },
  saveEditItem() {
    this.$refs.editItemForm.validate((valid) => {
      if (valid) {
        // 如果是日程提醒类型，需要验证是否选择了会议室
        if (this.editItem.type === '会议' && !this.editItem.boardroomId &&this.baseType!=='会议') {
          this.$message.warning('请选择会议室');
          return;
        }

        this.editItem.receiverList = this.editReceiverList;
        updateSchedule(this.editItem).then(response => {
          this.$message.success('日程信息更新成功');
          this.showEditModal = false;
          this.logItem.mn = "saveEditItem";
          this.logItem.opn = "编辑日程";
          this.logItem.res = "true";
          addLog(this.logItem);
          // 刷新页面
          window.location.reload();
        }).catch(error => {
          console.error('更新失败:', error);
          this.$message.error('日程信息更新失败');
          this.logItem.mn = "saveEditItem";
          this.logItem.opn = "编辑日程";
          this.logItem.res = "false";
          addLog(this.logItem);
        });
      } else {
        return false;
      }
    });
  },
  handlePageChange(page) {
    this.currentBoardroomPage = page;
  }
  } 
}
</script>

<style lang="less" scoped>
.fulltable{
  margin-top: 20px;
  height: 700px;

}
.full{
  height: 800px;
  margin: 0;
  padding: 0;
  background: pink;
  padding-top:10px;
  margin-left: 20px;
  margin-right: 20px;
  border-radius: 10px;
  flex: 1;
}
.add{
  padding: 10px;
}
/deep/.el-table .cell {  
  color: black;
}  
.button{
  background: #788fd3;
  color: white;
}

.paging{
  margin: 0;
  padding: 0;
  padding-top:10px;
  margin-left: 20px;
  margin-right: 20px;
  border-radius: 10px;
  flex: 1;

  /deep/ .el-pagination {
    display: flex;  
    justify-content: flex-end;  
  }
}
.search-box {
  display: flex;
  align-items: center;
}
</style>